var supplierObj = [];
var limit = 15;
var tid,storageId=-1;
var oldInventoryTime = '';
var orgObj = convertOrgToObj(orgList);
layui.use(['laypage','laydate', 'table', 'form'], function(){
    var table = layui.table;
    var form = layui.form;

    $("#add-inventoryTime").datePicker({
        format:"YYYY-MM-DD HH:mm:ss", //格式化
        singleDate:true,  //单选日期
    });

    $("#update-inventoryTime").datePicker({
        format:"YYYY-MM-DD HH:mm:ss", //格式化
        singleDate:true,  //单选日期
    });
    loadLineList({});

    let todoCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'orgId', title: '公司名称', width:100,  align: 'center',templet:function (val) {
                return orgObj[val.orgId];
            }}
            ,{field: 'code', title: '编码', width: 130, align: 'center',templet: function (val) {
                if (isNull(val.code)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.code + '</div>';
            }}
            ,{field: 'name', title: '名称', width: 160, align: 'center',templet: function (val) {
                if (isNull(val.name)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.name + '</div>';
            }}
            ,{field: 'type', title: '仓位类型', width:100, align: 'center', templet:function (val) {
                if (val.type == 0)
                    return '筒仓';
                else if (val.type == 1)
                    return '堆场';
                else
                    return '无类型';
            }}
            ,{field: 'maxCapacity', title: '最大容量(吨)', width: 100, align: 'center', templet:function (val) {
                var maxCapacity = val.maxCapacity;
                if (maxCapacity != null)
                    maxCapacity = parseFloat(maxCapacity / 1000).toFixed(2);
                else
                    maxCapacity = 0;
                return maxCapacity;
            }}
            ,{field: 'material', title: '材料', width: 160, align: 'center'}
            ,{field: 'lineName', title: '生产线名称', width: 160, align: 'center'}
            ,{field: 'isEnjoy', title: '共享仓', width: 120, align: 'center', templet:function (val) {
                if (val.isEnjoy == 0)
                    return '共享仓';
                else
                    return '非共享仓';
            }}
            ,{field: 'isStore', title: '是否显示库存', width: 120, align: 'center', templet:function (val) {
                if (val.isStore == 0)
                    return '显示';
                else
                    return '不显示';
            }}
            ,{field: 'isInventory', title: '是否参与盘存', width: 120, align: 'center', templet:function (val) {
                if (val.isInventory == 0)
                    return '是';
                else
                    return '否';
            }}
            ,{field: 'inventoryTime', title: '盘点时间', width: 180, align: 'center'}
            ,{field: 'status', title: '状态', width:130,align: 'center', templet:function (val) {
                if (val.status == 0)
                    return '启用';
                else
                    return '禁用';
            }}
            ,{field: 'remark', title: '备注', width: 220, align: 'center'}
            ,{field: 'creator', title: '创建人', width: 120, align: 'center'}
            ,{field: 'createTime', title: '创建时间', width: 200, align: 'center'}
            ,{fixed: 'right', title:'操作', width: 280, align:'center', templet:function (val) {
                var str = '<a lay-event="detail" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-primary">详情</a>';
                if (isUpdate == 1)
                    str += '<a lay-event="link" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger" style="background: #1e9fff;">关联生产线</a>';
                if (val.status == 0){
                    if (isDelete == 1)
                        str += '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">禁用</a>';
                    if (isUpdate == 1)
                        str += '<a lay-event="edit" href="javascript:void(0)" class="layui-btn layui-btn-xs">编辑</a>';
                }else{
                    if (isDelete == 1)
                        str += '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">启用</a>';
                }
                str += '<a lay-event="qrcode" href="javascript:void(0)" class="layui-btn layui-btn-xs" style="background: #1E9FFF;">二维码</a>';
                return str;
            }}
        ]
    ];
    let storageCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'code', title: '编号', width:100,  align: 'center'}
            ,{field: 'name', title: '生产线', width: 130, align: 'center'}
            ,{fixed: 'right', title:'操作', width: 160, align:'center', templet:function (val) {
                var str = '';
                if (isUpdate == 1) {
                    if (val.status == 0){
                        str += '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">取消关联</a>';
                    }else{
                        str += '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs">关联</a>';
                    }
                }
                return str;
            }}
        ]
    ];
    table.render({
        elem: '#body-list'
        ,url: '/system/storage/page'
        ,method: 'post'
        ,page: true
        ,contentType: 'application/json'
        ,cols: todoCols
        ,limit: limit
        ,limits: [15,30,50,100]
        ,request: {
            pageName: 'curr' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        ,where: {
            offset: 0,
            limit: limit,
            orgId:$('.search-origin').val(),
        }
        ,parseData: function(res){ //res 即为原始返回的数据
            console.log(res);
            if (res.code == 0 && res.data != null) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            } else {
                return {
                    "code": res.code, //解析接口状态
                    "msg": '没有任何数据', //解析提示文本
                    "count": 0, //解析数据长度
                    "data": '' //解析数据列表
                };
            }
        }
    });

    //监听行工具事件
    table.on('tool(body-list)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
        if(layEvent === 'delete'){
            var id = data.id;
            var status = data.status;
            var tip = '是否要启用？';
            if (status == 0)
                tip = '是否要禁用？';
            layer.confirm(tip, {
                btn: ['确定', '取消']
            }, function(index, layero){
                var updateStatus = 0;
                if (status == 0)
                    updateStatus = 1;
                var option =  '{"id": '+id+', "status":'+updateStatus+'}';
                save(option, "/system/storage/updatestatus");
            }, function(index){
            });
        } else if(layEvent === 'edit'){
            tid = data.id;
            $("#updateTitle").text("修改新增仓位信息");
            $('#update-mainDiscount-body').show();
            $(".update-search-origin").val(data.orgId);
            $(".update-code").val(data.code);
            $(".update-name").val(data.name);
            $(".update-type").val(data.type);
            $(".update-isEnjoy").val(data.isEnjoy);
            $(".update-isStore").val(data.isStore);
            $(".update-isInventory").val(data.isInventory);
            if (!isNull(data.materialId))
                $(".update-material").val(data.materialId);
            oldInventoryTime = data.inventoryTime;
            $(".update-maxCapacity").val(data.maxCapacity / 1000);
            $(".update-inventoryTime").val(data.inventoryTime);
            $(".update-remark").val(data.remark);
            $("#updateBtn").show();
            form.render();
        } else  if(layEvent === 'detail'){
            $("#updateTitle").text("查看新增仓位信息");
            $('#update-mainDiscount-body').show();
            $(".update-search-origin").val(data.orgId);
            $(".update-code").val(data.code);
            $(".update-name").val(data.name);
            $(".update-type").val(data.type);
            $(".update-isEnjoy").val(data.isEnjoy);
            $(".update-isStore").val(data.isStore);
            $(".update-isInventory").val(data.isInventory);
            if (!isNull(data.materialId))
                $(".update-material").val(data.materialId);
            $(".update-lineName").val(data.lineName);
            $(".update-maxCapacity").val(data.maxCapacity / 1000);
            $(".update-inventoryTime").val(data.inventoryTime);
            $(".update-remark").val(data.remark);
            $("#updateBtn").hide();
            form.render();
        } else if (layEvent == 'link') {
            $('.lineModal').show();
            storageId = data.id;
            $('.updateLineTitle').html(data.name + '-->关联生产线信息');
            table.render({
                elem: '#line-body-list'
                ,url: '/system/storage/find-storage'
                ,method: 'post'
                ,width:'90%'
                ,limit:1000
                ,cols: storageCols
                ,even: true
                ,where: {
                    storageId:data.id
                }
                ,parseData: function(res){ //res 即为原始返回的数据
                    console.log(res)
                    if (res.code == 0 && res.data != null) {
                        return {
                            "code": res.code, //解析接口状态
                            "msg": res.msg, //解析提示文本
                            "count": 0, //解析数据长度
                            "data": res.data //解析数据列表
                        };
                    } else {
                        return {
                            "code": res.code, //解析接口状态
                            "msg": '没有任何数据', //解析提示文本
                            "count": 0, //解析数据长度
                            "data": '' //解析数据列表
                        };
                    }
                }
            });
        } else if (layEvent == 'qrcode') {
            var text = data.qrcode;
            var config={
                width:200,
                height:200,
                text: text
            }
            layer.open({
                type: 1,
                area: ['420px', '340px'], // 宽高
                title: false,
                content: '<div class="qrcode-body">' +
                    '<div class="qrcode" style="text-align: center;margin-top: 50px;"></div>' +
                    '<div class="layui-inline" style="width: 97%;text-align: center;">' +
                    '<label class="layui-form-label" style="text-align: center;width: 95%;font-size: 22px;color: #dc322f;">'
                    + data.name + '</label></div></div>',
                move: '#ID-test-layer-move'
            });
            //
            $('.layui-layer-content').find(".qrcode").qrcode(config);
        }
    });
    table.on('tool(line-body-list)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
        if(layEvent === 'delete'){
            var id = data.id;
            var status = data.status;
            var tip = '是否要添加关联？';
            if (status == 0)
                tip = '是否要取消关联？';
            layer.confirm(tip, {
                btn: ['确定', '取消']
            }, function(index, layero){
                var updateStatus = 0;
                if (status == 0)
                    updateStatus = 1;
                var option = {
                    storageId:storageId,
                    lineId:data.lineId,
                    status: updateStatus,
                    orgId:$('.search-origin').val()
                };
                console.log(option)
                if (data.id != null) {
                    option['id'] = id;
                    saveLine(option, "/system/storage/update-storage-line");
                } else {
                    saveLine(option, "/system/storage/save-storage-line");
                }
                layer.close(index);
            });
        }
    });
    form.on('select(search-status)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-type)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-origin)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-line)', function(data) {
        $(".btn-query").trigger("click");
    });

    $('.btn-query').on('click', function () {//搜索按钮
        var searchVal = $('.search-text').val();
        var status = $('.search-status').val();
        var orgId = $('.search-origin').val();
        var type = $('.search-type').val();
        var lineId = $('.search-line').val();

        var option = {page:1,limit:limit,offset:0};
        if (!isNull(searchVal))
            option['searchVal'] = searchVal;
        if (!isNull(orgId))
            option['orgId'] = orgId;
        if (!isNull(status))
            option['status'] = status;
        if (!isNull(type))
            option['type'] = type;
        if (!isNull(lineId))
            option['lineId'] = lineId;
        table.reload('body-list', {
            where: option
        });
    });

    $("#update-mainDiscount-body .close").on("click", function() {
        $("#update-mainDiscount-body").hide();
        $("#update-mainDiscount-body-body input").val("");
        $("#update-mainDiscount-body select").val("");
        $("#update-mainDiscount-body textarea").val("");
        $(".qrcode-show").hide();
        form.render();
        tid = -1;
    });

    form.on('submit(updateBtns)', function() {
        if (isUpdate == 0) {
            layer.msg('您没有修改权限~！');
            return;
        }
        var orgId = $(".update-search-origin").val();
        var isEnjoy = $(".update-isEnjoy").val();
        var isStore = $(".update-isStore").val();
        var isInventory = $(".update-isInventory").val();
        var code = $(".update-code").val();
        var name = $(".update-name").val();
        var maxCapacity = $(".update-maxCapacity").val();
        var inventoryTime = $(".update-inventoryTime").val();
        var remark = $(".update-remark").val();
        var type = $(".update-type").val();
        var materialId = $(".update-material").val();
        var storeType = $(".update-material").find('option:selected').attr('data-storeType');
        var material = $.trim($(".update-material").find("option:selected").text());//公司
        console.log(storeType + '   ' + type)
        if (storeType != type) {
            layer.msg('材料仓位类型与ERP仓位类型不匹配~！');
            return ;
        }
        maxCapacity = maxCapacity * 1000;
        var option = {orgId:orgId,isEnjoy:isEnjoy,isStore:isStore,code:code,
            name:name,maxCapacity:maxCapacity,inventoryTime:inventoryTime,type:type,
            isInventory:isInventory,materialId:materialId,material:material,id:tid};
        if (!isNull(remark))
            option['remark'] = remark;
        if (isNull(tid) || tid == -1) {
            layer.msg("获取修改信息错误,请刷新再试！");
            return ;
        }
        var flag = 1;
        if (!isNull(inventoryTime) && !isNull(oldInventoryTime) && oldInventoryTime == inventoryTime) {
            layer.confirm('仓位盘存时间' + inventoryTime + '未发生变更,确认是否更新', {
                btn: ['确定', '取消']
            }, function(index, layero){
                save(JSON.stringify(option), "/system/storage/update");
                layer.close(index);
            }, function(index, layero){
                layer.close(index);
            });
        } else {
            save(JSON.stringify(option), "/system/storage/update");
        }
    });


    //新增页面选择类型
    form.on('select(add-search-origin)', function(data) {
        // loadLineList({orgId: $(".add-search-origin").val()});
    });

    //打开新增页面
    $('.btn-add').on('click', function () {//新增流程
        if (isInsert == 0) {
            layer.msg('您没有修改权限~！');
            return;
        }
        $('.addModal').show();
        $(".add-weight-show").show();
        $(".add-rate-show").hide();
    });

    //关闭新增页面
    $(".addModal .close").on("click", function () {//关闭新增流程窗口
        $(".addModal").hide();
        $(".addModal input").val("");
        $(".addModal select").val("");
        $(".addModal textarea").val("");
        form.render();
    });
    $(".lineModal .close").on("click", function () {//关闭
        $(".lineModal").hide();
    });

    //新增
    form.on('submit(addBtns)', function () {
        var orgId = $(".add-search-origin").val();
        var isEnjoy = $(".add-isEnjoy").val();
        var isStore = $(".add-isStore").val();
        var isInventory = $(".add-isInventory").val();
        var code = $(".add-code").val();
        var name = $(".add-name").val();
        var maxCapacity = $(".add-maxCapacity").val();
        var inventoryTime = $(".add-inventoryTime").val();
        var remark = $(".add-remark").val();
        var type = $(".add-type").val();
        var materialId = $(".add-material").val();
        var storeType = $(".add-material").find('option:selected').attr('data-storeType');
        var material = $.trim($(".add-material").find("option:selected").text());//公司
        if (storeType != type) {
            layer.msg('材料仓位类型与ERP仓位类型不匹配~！');
            return ;
        }
        maxCapacity = maxCapacity * 1000;
        var option = {orgId:orgId,isEnjoy:isEnjoy,isStore:isStore,code:code,
            name:name,maxCapacity:maxCapacity,inventoryTime:inventoryTime,type:type,
            isInventory:isInventory,materialId:materialId,material:material};
        if (!isNull(remark))
            option['remark'] = remark;
        save(JSON.stringify(option),"/system/storage/save");
    });


    function save(option, url) {//新增或修改
        var loading = layer.load(1);
        console.log(option);
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json',
            data: option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    layer.msg("保存成功!");
                    $(".btn-query").trigger("click");
                    $("#update-mainDiscount-body").hide();
                    $("#update-mainDiscount-body input").val("");
                    $("#update-mainDiscount-body select").val("");
                    $("#update-mainDiscount-body textarea").val("");
                    $("#add-mainDiscount-body").hide();
                    $("#add-mainDiscount-body input").val("");
                    $("#add-mainDiscount-body select").val("");
                    $("#add-mainDiscount-body textarea").val("");
                    form.render();
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }
    function saveLine(option, url) {//新增或修改
        var loading = layer.load(1);
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            data: option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    layer.msg("保存成功!");
                    $(".btn-query").trigger("click");
                    table.reload('line-body-list', { where: {storageId:storageId} });
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }


    //根据公司标识查询生产线数据
    function loadLineList(obj) {
        var loading = layer.load(1);
        $.ajax({
            url: '/system/sysLine/find-all',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: obj,
            success: function (res) {
                layer.close(loading);
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择生产线</option>';
                    $.each(data, function (i, v) {
                        html += '<option value="' + v.id + '">' + v.code + '[' + v.name + ']' + '</option>';
                    });
                    $('.search-line').html(html);
                    $('.update-line').html(html);
                } else {
                    $('.add-line').html('<option value="">暂无数据</option>');
                    $('.update-line').html('<option value="">暂无数据</option>');
                }
                if (!isNull(obj.lineId)) {
                    $('.update-line').val(obj.lineId);
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }

    $(document).keyup(function (event) {
        if (event.keyCode == 13) {
            $(".btn-query").trigger("click");
        }
    });
});